﻿using System;
using System.Text;
using Volo.Abp.Caching;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Json;

namespace Xms.Abp.Caching;

[Dependency(ReplaceServices = true)]
[ExposeServices(typeof(IDistributedCacheSerializer))]
public class XmsCacheSerializer : IDistributedCacheSerializer, ITransientDependency
{
    protected IJsonSerializer JsonSerializer { get; }

    public XmsCacheSerializer(IJsonSerializer jsonSerializer)
    {
        JsonSerializer = jsonSerializer;
    }

    public T Deserialize<T>(byte[] bytes)
    {
        var type = typeof(T);
        if (type == typeof(string))
        {
            return (T)((object)Encoding.UTF8.GetString(bytes));
        }
        else if (type.IsValueType)
        {
            return (T)Convert.ChangeType(Encoding.UTF8.GetString(bytes), type);
        }
        return (T)JsonSerializer.Deserialize(typeof(T), Encoding.UTF8.GetString(bytes));
    }

    public byte[] Serialize<T>(T obj)
    {
        if (obj is string str)
        {
            return Encoding.UTF8.GetBytes(str);
        }
        else if(typeof(T).IsValueType)
        {
            return Encoding.UTF8.GetBytes(obj.ToString());
        }
        return Encoding.UTF8.GetBytes(JsonSerializer.Serialize(obj));
    }
}
